package com.yunji.system.aspectj;

import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.exception.ServiceException;
import com.yunji.common.exception.device.DeviceException;
import com.yunji.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLSyntaxErrorException;
import java.util.Objects;

import static com.yunji.common.constant.HTTPStatus.*;

/**
 * 全局异常处理器
 *
 * @author yunji
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logs = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Resource
    HttpServletRequest request;

    /**
     * @author : peter-zhu
     * @date : 2025/1/16 13:48
     * @description : 设备异常统一
     */
    @ExceptionHandler(DeviceException.class)
    public Response<String> handleAccessDeniedException(DeviceException dv) {
        logs.error("DeviceException error:{}", dv.getMessage());
        return ResponseHelper.failure(dv.getCode(), dv.getMessage());
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Response<String> handleAccessDeniedException(AccessDeniedException e) {
        String requestURI = request.getRequestURI();
        logs.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return ResponseHelper.failure(FORBIDDEN, "没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response<String> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        String requestURI = request.getRequestURI();
        logs.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResponseHelper.failure(NOT_FOUND, "访问方式异常");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Response<String> handleServiceException(ServiceException e) {
        logs.error("ServiceException msg:{},detailMsg:{}", e.getMessage(), e.getDetailMessage());
        Integer code = e.getCode();
        return BeanUtils.isNotNull(code) ? ResponseHelper.failure(code, e.getMessage()) : ResponseHelper.failure(BUSINESS, e.getMessage());
    }

    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public Response<String> handleMissingPathVariableException(MissingPathVariableException e) {
        String requestURI = request.getRequestURI();
        logs.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
        return ResponseHelper.failure(BAD_REQUEST, String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Response<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        logs.info("【全局异常】参数类型异常");
        String requestURI = request.getRequestURI();
        logs.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
        return ResponseHelper.failure(BAD_REQUEST, String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), Objects.requireNonNull(e.getRequiredType()).getName(), e.getValue()));
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Response<String> handleRuntimeException(RuntimeException e) {
        String requestURI = request.getRequestURI();
        logs.error("请求地址'{}',发生未知异常.", requestURI, e);
        if (e.getCause() instanceof SQLSyntaxErrorException) {
            return ResponseHelper.failure(BUSINESS, "系统数据执行出错");
        }
        return ResponseHelper.failure(BUSINESS, e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Response<String> handleException(IllegalArgumentException e) {
        String requestURI = request.getRequestURI();
        logs.error("请求地址'{}',发生系统异常.异常信息{}", requestURI, e.getMessage());
        return ResponseHelper.failure(BUSINESS, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Response<String> handleException(Exception e) {
        String requestURI = request.getRequestURI();
        logs.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResponseHelper.failure("系统异常,请查看日志信息");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Response<String> handleBindException(BindException e) {
        logs.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ResponseHelper.failure(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logs.error(e.getMessage(), e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return ResponseHelper.failure(BUSINESS, message);
    }


//    @ExceptionHandler(DemoModeException.class)
//    public Response<String> handleDemoModeException(DemoModeException e) {
//        return ResponseHelper.failure("演示模式，不允许操作");
//    }
}
